<html lang="en-US">

<head>
    
<title>「连载二」gRPC Client and Server - 花落雨忧</title>

<meta property="og:title" content="「连载二」gRPC Client and Server - 花落雨忧">



    



    
    <meta property="description" content="本章节将使用 Go 来编写 gRPC Server 和 Client，让其互相通讯。在此之上会使用到如下库：
[&amp;hellip;] go get -u google.golang.org/grpc Protocol Buffers v3 wget &amp;hellip;">
    <meta property="og:description" content="本章节将使用 Go 来编写 gRPC Server 和 Client，让其互相通讯。在此之上会使用到如下库：
[&amp;hellip;] go get -u google.golang.org/grpc Protocol Buffers v3 wget &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/grpc/2018-09-23-client-and-server/">「连载二」gRPC Client and Server</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/09/23</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="前言">前言</h2>
<p>本章节将使用 Go 来编写 gRPC Server 和 Client，让其互相通讯。在此之上会使用到如下库：</p>
<ul>
<li>google.golang.org/grpc</li>
<li>github.com/golang/protobuf/protoc-gen-go</li>
</ul>
<h2 id="安装">安装</h2>
<h3 id="grpc">gRPC</h3>
<pre><code>go get -u google.golang.org/grpc
</code></pre><h3 id="protocol-buffers-v3">Protocol Buffers v3</h3>
<pre><code>wget https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-all-3.5.1.zip
unzip protobuf-all-3.5.1.zip
cd protobuf-3.5.1/
./configure
make
make install
</code></pre><p>检查是否安装成功</p>
<pre><code>protoc --version
</code></pre><p>若出现以下错误，执行 <code>ldconfig</code> 命名就能解决这问题</p>
<pre><code>protoc: error while loading shared libraries: libprotobuf.so.15: cannot open shared object file: No such file or directory
</code></pre><h3 id="protoc-plugin">Protoc Plugin</h3>
<pre><code>go get -u github.com/golang/protobuf/protoc-gen-go
</code></pre><p>安装环境若有问题，可参考我先前的文章 <a href="https://segmentfault.com/a/1190000013339403">《介绍与环境安装》</a> 内有详细介绍，不再赘述</p>
<h2 id="grpc-1">gRPC</h2>
<p>本小节开始正式编写 gRPC 相关的程序，一起上车吧 😄</p>
<h3 id="图示">图示</h3>
<p><img src="https://image.eddycjy.com/415d9544fce1e774e1095ab99b6cc015.png" alt="image"></p>
<h3 id="目录结构">目录结构</h3>
<pre><code>$ tree go-grpc-example
go-grpc-example
├── client
├── proto
│   └── search.proto
└── server.go
</code></pre><h3 id="idl">IDL</h3>
<h4 id="编写">编写</h4>
<p>在 proto 文件夹下的 search.proto 文件中，写入如下内容：</p>
<pre><code>syntax = &quot;proto3&quot;;

package proto;

service SearchService {
    rpc Search(SearchRequest) returns (SearchResponse) {}
}

message SearchRequest {
    string request = 1;
}

message SearchResponse {
    string response = 1;
}
</code></pre><h4 id="生成">生成</h4>
<p>在 proto 文件夹下执行如下命令：</p>
<pre><code>$ protoc --go_out=plugins=grpc:. *.proto
</code></pre><ul>
<li>plugins=plugin1+plugin2：指定要加载的子插件列表</li>
</ul>
<p>我们定义的 proto 文件是涉及了 RPC 服务的，而默认是不会生成 RPC 代码的，因此需要给出 <code>plugins</code> 参数传递给 <code>protoc-gen-go</code>，告诉它，请支持 RPC（这里指定了 gRPC）</p>
<ul>
<li>&ndash;go_out=.：设置 Go 代码输出的目录</li>
</ul>
<p>该指令会加载 protoc-gen-go 插件达到生成 Go 代码的目的，生成的文件以 .pb.go 为文件后缀</p>
<ul>
<li>: （冒号）</li>
</ul>
<p>冒号充当分隔符的作用，后跟所需要的参数集。如果这处不涉及 RPC，命令可简化为：</p>
<pre><code>$ protoc --go_out=. *.proto
</code></pre><p>注：建议你看看两条命令生成的 .pb.go 文件，分别有什么区别</p>
<h4 id="生成后">生成后</h4>
<p>执行完毕命令后，将得到一个 .pb.go 文件，文件内容如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">SearchRequest</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Request</span>              <span style="color:#66d9ef">string</span>   <span style="color:#e6db74">`protobuf:&#34;bytes,1,opt,name=request&#34; json:&#34;request,omitempty&#34;`</span>
	<span style="color:#a6e22e">XXX_NoUnkeyedLiteral</span> <span style="color:#66d9ef">struct</span>{} <span style="color:#e6db74">`json:&#34;-&#34;`</span>
	<span style="color:#a6e22e">XXX_unrecognized</span>     []<span style="color:#66d9ef">byte</span>   <span style="color:#e6db74">`json:&#34;-&#34;`</span>
	<span style="color:#a6e22e">XXX_sizecache</span>        <span style="color:#66d9ef">int32</span>    <span style="color:#e6db74">`json:&#34;-&#34;`</span>
}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">m</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">SearchRequest</span>) <span style="color:#a6e22e">Reset</span>()         { <span style="color:#f92672">*</span><span style="color:#a6e22e">m</span> = <span style="color:#a6e22e">SearchRequest</span>{} }
<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">m</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">SearchRequest</span>) <span style="color:#a6e22e">String</span>() <span style="color:#66d9ef">string</span> { <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">proto</span>.<span style="color:#a6e22e">CompactTextString</span>(<span style="color:#a6e22e">m</span>) }
<span style="color:#66d9ef">func</span> (<span style="color:#f92672">*</span><span style="color:#a6e22e">SearchRequest</span>) <span style="color:#a6e22e">ProtoMessage</span>()    {}
<span style="color:#66d9ef">func</span> (<span style="color:#f92672">*</span><span style="color:#a6e22e">SearchRequest</span>) <span style="color:#a6e22e">Descriptor</span>() ([]<span style="color:#66d9ef">byte</span>, []<span style="color:#66d9ef">int</span>) {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fileDescriptor_search_8b45f79ee13ff6a3</span>, []<span style="color:#66d9ef">int</span>{<span style="color:#ae81ff">0</span>}
}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">m</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">SearchRequest</span>) <span style="color:#a6e22e">GetRequest</span>() <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">m</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">m</span>.<span style="color:#a6e22e">Request</span>
	}
	<span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;&#34;</span>
}
</code></pre></div><p>通过阅读这一部分代码，可以知道主要涉及如下方面：</p>
<ul>
<li>字段名称从小写下划线转换为大写驼峰模式（字段导出）</li>
<li>生成一组 Getters 方法，能便于处理一些空指针取值的情况</li>
<li>ProtoMessage 方法实现 proto.Message 的接口</li>
<li>生成 Rest 方法，便于将 Protobuf 结构体恢复为零值</li>
<li>Repeated 转换为切片</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">SearchRequest</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Request</span>              <span style="color:#66d9ef">string</span>   <span style="color:#e6db74">`protobuf:&#34;bytes,1,opt,name=request&#34; json:&#34;request,omitempty&#34;`</span>
}

<span style="color:#66d9ef">func</span> (<span style="color:#f92672">*</span><span style="color:#a6e22e">SearchRequest</span>) <span style="color:#a6e22e">Descriptor</span>() ([]<span style="color:#66d9ef">byte</span>, []<span style="color:#66d9ef">int</span>) {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fileDescriptor_search_8b45f79ee13ff6a3</span>, []<span style="color:#66d9ef">int</span>{<span style="color:#ae81ff">0</span>}
}

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">SearchResponse</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Response</span>             <span style="color:#66d9ef">string</span>   <span style="color:#e6db74">`protobuf:&#34;bytes,1,opt,name=response&#34; json:&#34;response,omitempty&#34;`</span>
}

<span style="color:#66d9ef">func</span> (<span style="color:#f92672">*</span><span style="color:#a6e22e">SearchResponse</span>) <span style="color:#a6e22e">Descriptor</span>() ([]<span style="color:#66d9ef">byte</span>, []<span style="color:#66d9ef">int</span>) {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fileDescriptor_search_8b45f79ee13ff6a3</span>, []<span style="color:#66d9ef">int</span>{<span style="color:#ae81ff">1</span>}
}

<span style="color:#f92672">...</span>

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">init</span>() { <span style="color:#a6e22e">proto</span>.<span style="color:#a6e22e">RegisterFile</span>(<span style="color:#e6db74">&#34;search.proto&#34;</span>, <span style="color:#a6e22e">fileDescriptor_search_8b45f79ee13ff6a3</span>) }

<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">fileDescriptor_search_8b45f79ee13ff6a3</span> = []<span style="color:#66d9ef">byte</span>{
	<span style="color:#75715e">// 131 bytes of a gzipped FileDescriptorProto
</span><span style="color:#75715e"></span>	<span style="color:#ae81ff">0x1f</span>, <span style="color:#ae81ff">0x8b</span>, <span style="color:#ae81ff">0x08</span>, <span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0x02</span>, <span style="color:#ae81ff">0xff</span>, <span style="color:#ae81ff">0xe2</span>, <span style="color:#ae81ff">0xe2</span>, <span style="color:#ae81ff">0x29</span>, <span style="color:#ae81ff">0x4e</span>, <span style="color:#ae81ff">0x4d</span>, <span style="color:#ae81ff">0x2c</span>,
	<span style="color:#ae81ff">0x4a</span>, <span style="color:#ae81ff">0xce</span>, <span style="color:#ae81ff">0xd0</span>, <span style="color:#ae81ff">0x2b</span>, <span style="color:#ae81ff">0x28</span>, <span style="color:#ae81ff">0xca</span>, <span style="color:#ae81ff">0x2f</span>, <span style="color:#ae81ff">0xc9</span>, <span style="color:#ae81ff">0x17</span>, <span style="color:#ae81ff">0x62</span>, <span style="color:#ae81ff">0x05</span>, <span style="color:#ae81ff">0x53</span>, <span style="color:#ae81ff">0x4a</span>, <span style="color:#ae81ff">0x9a</span>, <span style="color:#ae81ff">0x5c</span>, <span style="color:#ae81ff">0xbc</span>,
	<span style="color:#ae81ff">0xc1</span>, <span style="color:#ae81ff">0x60</span>, <span style="color:#ae81ff">0xe1</span>, <span style="color:#ae81ff">0xa0</span>, <span style="color:#ae81ff">0xd4</span>, <span style="color:#ae81ff">0xc2</span>, <span style="color:#ae81ff">0xd2</span>, <span style="color:#ae81ff">0xd4</span>, <span style="color:#ae81ff">0xe2</span>, <span style="color:#ae81ff">0x12</span>, <span style="color:#ae81ff">0x21</span>, <span style="color:#ae81ff">0x09</span>, <span style="color:#ae81ff">0x2e</span>, <span style="color:#ae81ff">0xf6</span>, <span style="color:#ae81ff">0x22</span>, <span style="color:#ae81ff">0x08</span>,
	<span style="color:#ae81ff">0x53</span>, <span style="color:#ae81ff">0x82</span>, <span style="color:#ae81ff">0x51</span>, <span style="color:#ae81ff">0x81</span>, <span style="color:#ae81ff">0x51</span>, <span style="color:#ae81ff">0x83</span>, <span style="color:#ae81ff">0x33</span>, <span style="color:#ae81ff">0x08</span>, <span style="color:#ae81ff">0xc6</span>, <span style="color:#ae81ff">0x55</span>, <span style="color:#ae81ff">0xd2</span>, <span style="color:#ae81ff">0xe1</span>, <span style="color:#ae81ff">0xe2</span>, <span style="color:#ae81ff">0x83</span>, <span style="color:#ae81ff">0x29</span>, <span style="color:#ae81ff">0x2d</span>,
	<span style="color:#ae81ff">0x2e</span>, <span style="color:#ae81ff">0xc8</span>, <span style="color:#ae81ff">0xcf</span>, <span style="color:#ae81ff">0x2b</span>, <span style="color:#ae81ff">0x4e</span>, <span style="color:#ae81ff">0x15</span>, <span style="color:#ae81ff">0x92</span>, <span style="color:#ae81ff">0xe2</span>, <span style="color:#ae81ff">0xe2</span>, <span style="color:#ae81ff">0x28</span>, <span style="color:#ae81ff">0x82</span>, <span style="color:#ae81ff">0xb2</span>, <span style="color:#ae81ff">0xa1</span>, <span style="color:#ae81ff">0x8a</span>, <span style="color:#ae81ff">0xe1</span>, <span style="color:#ae81ff">0x7c</span>,
	<span style="color:#ae81ff">0x23</span>, <span style="color:#ae81ff">0x0f</span>, <span style="color:#ae81ff">0x98</span>, <span style="color:#ae81ff">0xc1</span>, <span style="color:#ae81ff">0xc1</span>, <span style="color:#ae81ff">0xa9</span>, <span style="color:#ae81ff">0x45</span>, <span style="color:#ae81ff">0x65</span>, <span style="color:#ae81ff">0x99</span>, <span style="color:#ae81ff">0xc9</span>, <span style="color:#ae81ff">0xa9</span>, <span style="color:#ae81ff">0x42</span>, <span style="color:#ae81ff">0xe6</span>, <span style="color:#ae81ff">0x5c</span>, <span style="color:#ae81ff">0x6c</span>, <span style="color:#ae81ff">0x10</span>,
	<span style="color:#ae81ff">0x01</span>, <span style="color:#ae81ff">0x21</span>, <span style="color:#ae81ff">0x11</span>, <span style="color:#ae81ff">0x88</span>, <span style="color:#ae81ff">0x13</span>, <span style="color:#ae81ff">0xf4</span>, <span style="color:#ae81ff">0x50</span>, <span style="color:#ae81ff">0x2c</span>, <span style="color:#ae81ff">0x96</span>, <span style="color:#ae81ff">0x12</span>, <span style="color:#ae81ff">0x45</span>, <span style="color:#ae81ff">0x13</span>, <span style="color:#ae81ff">0x85</span>, <span style="color:#ae81ff">0x98</span>, <span style="color:#ae81ff">0xa3</span>, <span style="color:#ae81ff">0xc4</span>,
	<span style="color:#ae81ff">0x90</span>, <span style="color:#ae81ff">0xc4</span>, <span style="color:#ae81ff">0x06</span>, <span style="color:#ae81ff">0x16</span>, <span style="color:#ae81ff">0x37</span>, <span style="color:#ae81ff">0x06</span>, <span style="color:#ae81ff">0x04</span>, <span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0xff</span>, <span style="color:#ae81ff">0xff</span>, <span style="color:#ae81ff">0xf3</span>, <span style="color:#ae81ff">0xba</span>, <span style="color:#ae81ff">0x74</span>, <span style="color:#ae81ff">0x95</span>, <span style="color:#ae81ff">0xc0</span>,
	<span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0x00</span>, <span style="color:#ae81ff">0x00</span>,
}
</code></pre></div><p>而这一部分代码主要是围绕 <code>fileDescriptor</code> 进行，在这里 <code>fileDescriptor_search_8b45f79ee13ff6a3</code> 表示一个编译后的 proto 文件，而每一个方法都包含 Descriptor 方法，代表着这一个方法在 <code>fileDescriptor</code> 中具体的 Message Field</p>
<h3 id="server">Server</h3>
<p>这一小节将编写 gRPC Server 的基础模板，完成一个方法的调用。对 server.go 写入如下内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;context&#34;</span>
	<span style="color:#e6db74">&#34;log&#34;</span>
	<span style="color:#e6db74">&#34;net&#34;</span>

	<span style="color:#e6db74">&#34;google.golang.org/grpc&#34;</span>

	<span style="color:#a6e22e">pb</span> <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-grpc-example/proto&#34;</span>
)

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">SearchService</span> <span style="color:#66d9ef">struct</span>{}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">s</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">SearchService</span>) <span style="color:#a6e22e">Search</span>(<span style="color:#a6e22e">ctx</span> <span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Context</span>, <span style="color:#a6e22e">r</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">SearchRequest</span>) (<span style="color:#f92672">*</span><span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">SearchResponse</span>, <span style="color:#66d9ef">error</span>) {
	<span style="color:#66d9ef">return</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">SearchResponse</span>{<span style="color:#a6e22e">Response</span>: <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GetRequest</span>() <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; Server&#34;</span>}, <span style="color:#66d9ef">nil</span>
}

<span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> = <span style="color:#e6db74">&#34;9001&#34;</span>

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">server</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">NewServer</span>()
	<span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">RegisterSearchServiceServer</span>(<span style="color:#a6e22e">server</span>, <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">SearchService</span>{})

	<span style="color:#a6e22e">lis</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">net</span>.<span style="color:#a6e22e">Listen</span>(<span style="color:#e6db74">&#34;tcp&#34;</span>, <span style="color:#e6db74">&#34;:&#34;</span><span style="color:#f92672">+</span><span style="color:#a6e22e">PORT</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;net.Listen err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">server</span>.<span style="color:#a6e22e">Serve</span>(<span style="color:#a6e22e">lis</span>)
}
</code></pre></div><ul>
<li>创建 gRPC Server 对象，你可以理解为它是 Server 端的抽象对象</li>
<li>将 SearchService（其包含需要被调用的服务端接口）注册到 gRPC Server 的内部注册中心。这样可以在接受到请求时，通过内部的服务发现，发现该服务端接口并转接进行逻辑处理</li>
<li>创建 Listen，监听 TCP 端口</li>
<li>gRPC Server 开始 lis.Accept，直到 Stop 或 GracefulStop</li>
</ul>
<h3 id="client">Client</h3>
<p>接下来编写 gRPC Go Client 的基础模板，打开 client/client.go 文件，写入以下内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;context&#34;</span>
	<span style="color:#e6db74">&#34;log&#34;</span>

	<span style="color:#e6db74">&#34;google.golang.org/grpc&#34;</span>

	<span style="color:#a6e22e">pb</span> <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-grpc-example/proto&#34;</span>
)

<span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> = <span style="color:#e6db74">&#34;9001&#34;</span>

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">conn</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">Dial</span>(<span style="color:#e6db74">&#34;:&#34;</span><span style="color:#f92672">+</span><span style="color:#a6e22e">PORT</span>, <span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">WithInsecure</span>())
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;grpc.Dial err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}
	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Close</span>()

	<span style="color:#a6e22e">client</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">NewSearchServiceClient</span>(<span style="color:#a6e22e">conn</span>)
	<span style="color:#a6e22e">resp</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">client</span>.<span style="color:#a6e22e">Search</span>(<span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Background</span>(), <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">SearchRequest</span>{
		<span style="color:#a6e22e">Request</span>: <span style="color:#e6db74">&#34;gRPC&#34;</span>,
	})
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;client.Search err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;resp: %s&#34;</span>, <span style="color:#a6e22e">resp</span>.<span style="color:#a6e22e">GetResponse</span>())
}
</code></pre></div><ul>
<li>创建与给定目标（服务端）的连接交互</li>
<li>创建 SearchService 的客户端对象</li>
<li>发送 RPC 请求，等待同步响应，得到回调后返回响应结果</li>
<li>输出响应结果</li>
</ul>
<h2 id="验证">验证</h2>
<h3 id="启动-server">启动 Server</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-sh" data-lang="sh">$ pwd
$GOPATH/github.com/EDDYCJY/go-grpc-example
$ go run server.go
</code></pre></div><h3 id="启动-client">启动 Client</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-sh" data-lang="sh">$ pwd
$GOPATH/github.com/EDDYCJY/go-grpc-example/client
$ go run client.go
2018/09/23 11:06:23 resp: gRPC Server
</code></pre></div><h2 id="总结">总结</h2>
<p>在本章节，我们对 Protobuf、gRPC Client/Server 分别都进行了介绍。希望你结合文中讲述内容再写一个 Demo 进行深入了解，肯定会更棒 🤔</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-grpc-example">go-grpc-example</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-09-22-install/">「连载一」gRPC及相关介绍</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/tools/2018-09-15-go-tool-pprof/">Go 大杀器之性能剖析 PProf</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-09-01-nginx/">「连载十七」用Nginx部署Go应用</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-08-26-makefile/">「番外」请入门 Makefile</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-07-07-font/">「连载十六」在图片上绘制文字</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/grpc" title="View all posts tagged match">grpc</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/grpc/2018-09-22-install/"
                                                    rel="prev">「连载一」gRPC及相关介绍</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/grpc/2018-09-24-stream-client-server/">「连载三」gRPC Streaming, Client and Server</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>